class RunnerImportController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, ngDialog, dialogService, RunnerService, fileReader, iRunner){

        const vm = this;

        vm.$rootScope    = $rootScope;
        vm.$cookieStore  = $cookieStore;
        vm.$timeout      = $timeout;
        vm.$state        = $state;
        vm.ngDialog      = ngDialog;
        vm.dialogService = dialogService;
        vm.RunnerService = RunnerService;
        vm.fileReader    = fileReader;
        vm.iRunner       = iRunner;

        $rootScope.showspinner = false;

        // notify
        const notify = '由于网络原因，导致上传文件中断，请清空数据后重新上传。';

        // 初始化进度条参数
        $rootScope.progress = '0%';
        $rootScope.total    = 0;
        $rootScope.begin    = 0;
        vm.isFile           = true;

        // 导入文件
        vm.getFile = () => {
            vm.fileReader.readAsDataUrl($scope.file, $scope)
            .then( result => {

                vm.isFile = true;
                
                //判断附件是否excel
                if(!/xl(sx|sm|tm|s|t)|o(ds|ts)|slk|xml|gnumeric|h(tm|tml)/.test($scope.file.name)){
                    $rootScope.isFile = false;
                    vm.dialogService.error('文件类型必须是xlsx, xlsm, xltm, xls, xlt, ods, ots, slk, xml, gnumeric, htm, html其中一种。');
                    return false;
                } else {
                    vm.submitForm();
                }

                console.log($scope.file)
            }, error => console.log('error'));
        }

        // 删除临时表
        function deleteTable(temp_runner) {
            vm.RunnerService.postRunnerImport({
                instance: temp_runner,
                progress: 'done'
            }, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
            .then( done => console.log(done));
        }

        // 转换秒
        function getDateDiff(time) {
            var total = time;
            var day       = parseInt(total / (24*60*60));       //计算整数天数
            var afterDay  = total - day*24*60*60;               //取得算出天数后剩余的秒数
            var hour      = parseInt(afterDay/(60*60));         //计算整数小时数
            var afterHour = total - day*24*60*60 - hour*60*60;  //取得算出小时数后剩余的秒数
            var min       = parseInt(afterHour/60);             //计算整数分
            var afterMin  = parseInt(total - day*24*60*60 - hour*60*60 - min*60);  //取得算出分后剩余的秒数
            
            if (day>0) {
                var year = Math.floor(day/365); //计算年数
                var month = Math.floor(day/30); //计算月数
                if (year>0) {
                    return year + '年';
                }
                if (month>0) {
                    return month + '月';
                }
                return day + '天';
            } else if (hour>0) {
                return hour + '小时'
            } else if (min>0) {
                return min + '分钟'
            } else {
                return afterMin + '秒'
            }
        }

        // 表单提交
        vm.submitForm = () => {

            // 验证失败, 提示用户
            if (!vm.myFile) {
                vm.dialogService.error('请选择需要上传的文件');
            }

            // 验证通过
            if (vm.myFile&&vm.isFile) {

                // 显示进度条
                $rootScope.progressBar = true;

                // 导入选手信息
                vm.RunnerService.postRunnerImport({file: vm.myFile}, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
                .then( data => {
                   
                    var status = '', temp_runner = '', start = '', total = '', dueTime = 0, offset = 0;


                                // 成功调用
                                if (data.code==0) {

                                    console.log(data);
                                    // return;

                                    // 开始导入，第一次导入
                                    if (data.data.progress=='import') {

                                        vm.RunnerService.postRunnerImport({
                                            instance: data.data.instance,
                                            progress: data.data.progress
                                        }, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
                                        .then( data3 => {

                                            console.log(data3);

                                            status      = data3.data.progress;
                                            temp_runner = data3.data.instance;
                                            start       = data3.data.start ? data3.data.start : '';
                                            total       = data3.data.total ? data3.data.total : '';
                                            offset      = data3.data.start ? data3.data.start : 0;
                                            dueTime     = data3.data.total ? getDateDiff( parseInt(data3.data.total) / 50 * 8 ) : 0;

                                            $rootScope.progress = data3.data.start && data3.data.total ? ((parseInt(start)/parseInt(total))*100).toFixed(2) + '%' : '100%';
                                            $rootScope.total    = data3.data.total ? data3.data.total : $rootScope.total;
                                            $rootScope.begin    = data3.data.start ? data3.data.start : $rootScope.total;
                                            $rootScope.dueTime  = dueTime;

                                            // 成功调用
                                            if (data3.code==0) {

                                                // 判断是否需要分页导入数据
                                                if (data3.data.progress=='import'&&data3.data.start) {
                                                    var importStart = (status, temp_runner, start) => {
                                                        vm.RunnerService.postRunnerImport({
                                                            instance: temp_runner,
                                                            progress: status,
                                                            start: start
                                                        }, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
                                                        .then( data4 => {
                                                            
                                                            status      = data4.data.progress;
                                                            temp_runner = data4.data.instance;
                                                            start       = data4.data.start ? data4.data.start : '';
                                                            total       = data4.data.total ? data4.data.total : '';
                                                            dueTime     = data4.data.total ? getDateDiff( (parseInt(data4.data.total) - parseInt(offset)) / 50 * 8 ) : 0;
                                                            offset      = data4.data.start ? data4.data.start : 0;

                                                            $rootScope.progress = data4.data.start && data4.data.total ? ((parseInt(start)/parseInt(total))*100).toFixed(2) + '%' : '100%';
                                                            $rootScope.total    = data4.data.total ? data4.data.total : $rootScope.total;
                                                            $rootScope.begin    = data4.data.start ? data4.data.start : $rootScope.total;
                                                            $rootScope.dueTime  = dueTime;
                                                            
                                                            // 成功调用
                                                            if (data4.code==0) {

                                                                // 分页导入数据
                                                                if (data4.data.progress=='import'&&data4.data.start) {
                                                                    importStart(status, temp_runner, start)
                                                                }

                                                                // 导入数据成功
                                                                if (data4.data.progress=='done'&&data4.data.error=='') {

                                                                    // 删除临时表
                                                                    deleteTable(temp_runner);

                                                                    $rootScope.progressBar = false;
                                                                    //跳转页面
                                                                    vm.$state.go('dashboard.race.runnerlist');
                                                                }

                                                                // 导入数据重复
                                                                if (data4.data.progress=='done'&&data4.data.error!='') {

                                                                    // 缓存错误信息链接
                                                                    $rootScope.error = data4.data.error;
                                                                    console.log($rootScope.error);

                                                                    // 删除临时表
                                                                    deleteTable(temp_runner);

                                                                    // 提示用户错误信息
                                                                    vm.$timeout( () => {
                                                                        $rootScope.progressBar = false;
                                                                        vm.ngDialog.open({
                                                                            template: '<h3>部分数据重复，点击查看</h3><a ng-href="{{error}}">{{error}}</a>',
                                                                            className: 'ngdialog-theme-default ngdialog-alert',
                                                                            plain: true,
                                                                            scope: $scope
                                                                        });
                                                                    }, 1500)
                                                                }
                                                                
                                                            }

                                                            console.log(data4)
                                                        }, error => {
                                                            vm.dialogService.error(notify);
                                                            console.log('error')
                                                        });
                                                    }

                                                    importStart(status, temp_runner, start);
                                                }

                                                // 导入数据成功
                                                if (data3.data.progress=='done'&&data3.data.error=='') {

                                                    $rootScope.progressBar = false;
                                                    //跳转页面
                                                    vm.$state.go('dashboard.race.runnerlist');

                                                }

                                                // 导入数据重复
                                                if (data3.data.progress=='done'&&data3.data.error!='') {

                                                    // 缓存错误信息链接
                                                    $rootScope.error = data3.data.error;

                                                    // 删除临时表
                                                    deleteTable(temp_runner);

                                                    // 提示用户错误信息
                                                    vm.$timeout( () => {
                                                        $rootScope.progressBar = false;
                                                        vm.ngDialog.open({
                                                            template: '<h3>部分数据重复，点击查看</h3><a ng-href="{{error}}">{{error}}</a>',
                                                            className: 'ngdialog-theme-default ngdialog-alert',
                                                            plain: true,
                                                            scope: $rootScope
                                                        });
                                                    }, 1500)

                                                    console.log($rootScope.error)
                                                }

                                            }

                                            console.log(data3)
                                        }, error => {
                                            vm.dialogService.error(notify);
                                            console.log('error')
                                        });
                                    }
                                } 
                            // }, error => {
                            //     vm.dialogService.error(notify);
                            //     console.log('error')
                            // });
                        // }

                    // }

                    // 表头格式错误
                    if (data.code==-6) {
                        $rootScope.progressBar = false;
                        vm.dialogService.error('表头格式错误。');
                    }

                    console.log(data)
                }, error => {
                    vm.dialogService.error(notify);
                    console.log('error')
                });
            }

            return false;
        }

    }
}

RunnerImportController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', 'ngDialog', 'dialogService', 'RunnerService', 'fileReader', 'iRunner']; 

export default RunnerImportController;